<?php
/**
 * DownloadExcelExe.class.php
 * - Download Excel
 * @author Longlt
 */
class DownloadExcelExe {

	/**
	 * __construct
	 * - Use constructor object
	 */
	public function __construct () {
		// Nothing
	}
	/**
	  * CreateByListControl
	  * - Create excel from template and List Control
	  * @param $name name data control
	  * @param $dataDynamic data dynamic for input cell excel
	  * @param $dataStatic data static for input cell excel
	  * @return void
	 */
	public function CreateByListControl($action, $dataDynamic, $totalDynamic = null) {
		/**
		 * Load Control
		 */
		/** Create a new Reader of the type defined in $inputFileType **/
		$objPHPExcel 	= new PHPExcel();
        $objReader 		= new PHPExcel_Reader_Excel5;

		// Load common control
		$configControl = isset($this->listControl[$action]) ? $this->listControl[$action] : array();

		// Load from Template Excel : Treatment $totalDynamic
		$totalDynamic		= ($totalDynamic != null) ? $totalDynamic : count($dataDynamic);
		$totalDynamicRound  = $totalDynamic - $totalDynamic % 50 + 50;


		/**  Advise the Reader of which WorkSheets we want to load, It's more efficient to limit sheet loading in this manner rather than coding it into a Read Filter  **/
		$objReader->setLoadSheetsOnly($configControl['sheet']);

		/**  Load only the rows and columns that match our filter from $inputFileName to a PHPExcel Object  **/
		$template		= $totalDynamicRound == null ? '' : $totalDynamicRound . '_' .$configControl['fileTpl'];
		try {
			$objPHPExcel 	= $objReader->load(Util::pathTemplateExcel($template));
		}
	    catch (Exception $e){
	    	throw new CHttpException(404,"Không tìm thấy template {$template}");
	    }

	    // Call function draw template
	    try {
	    	$objPHPExcel = call_user_func_array(array("DownloadExcel", $action), array($objPHPExcel, $dataDynamic ));
	    }
	    catch (Exception $e){
	    	throw new CHttpException(404,"Không tìm thấy function {$action}");
	    }


	    /**
	     * output
	     */
		$nameOutput	= $configControl['fileOutput'] . '_' . date('YmdHis') . '.xls';
	    $this->outPut($objPHPExcel, $nameOutput);
	}

	/**
	  * output
	  * - output excel into browser
	  * @param $objPHPExcel object excel
	  * @param $fileNameExcel file name excel
	 */
	public function output($objPHPExcel, $fileNameExcel) {
		// Redirect output to a client web browser (Excel5)
		header('Pragma: ');
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.$fileNameExcel.'"');
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

		$objWriter->save('php://output');
	}
}
?>